"""
季节性策略(月度效应)
策略逻辑：
1. 基于历史月度表现数据
2. 在表现最好的月份做多
3. 在表现最差的月份做空
"""

import pandas as pd
import numpy as np
import pyfolio as pf

def seasonality_strategy(prices, lookback_years=10):
    """
    季节性策略
    
    参数:
        prices: 价格序列
        lookback_years: 历史数据年数
    
    返回:
        positions: 持仓序列
    """
    # 计算月度收益
    monthly_returns = prices.resample('M').last().pct_change()
    
    # 计算历史各月平均收益
    seasonal_pattern = monthly_returns.groupby(
        monthly_returns.index.month
    ).mean().sort_values()
    
    # 确定最佳和最差月份
    best_month = seasonal_pattern.idxmax()
    worst_month = seasonal_pattern.idxmin()
    
    # 生成交易信号
    positions = pd.Series(0, index=prices.index)
    current_month = None
    
    for date in prices.index:
        if date.month != current_month:
            current_month = date.month
            if current_month == best_month:
                positions[date] = 1  # 做多
            elif current_month == worst_month:
                positions[date] = -1  # 做空
            else:
                positions[date] = 0  # 空仓
    
    return positions

if __name__ == '__main__':
    # 示例用法
    import yfinance as yf
    
    # 获取示例数据
    data = yf.download('SPY', start='2010-01-01', end='2023-01-01')['Close']
    
    # 运行策略
    positions = seasonality_strategy(data)
    
    # 计算收益
    returns = positions.shift(1) * data.pct_change()
    pf.create_returns_tear_sheet(returns)